<template>
  <div class="wrapper-scroll">
    <div class="menu">
      <ul>
        <li v-for="(item, index) in [...menu, ...dynamicMenu]" :key="index" class="menu-item" @click="handleClick(index)">
          <el-button type="text" :class="getCurrentIndex() == index ? '' : 'el_button_text'">
            <strong>{{ item.label }}</strong>
          </el-button>
        </li>
      </ul>
      <ul v-if="!windowValue && isShowopenDialogVisible.isShow">
        <li>
          <el-link
            type="primary"
            style="font-size: 14px"
            @click="
              () => {
                this.$emit('openDialogVisible', isShowopenDialogVisible)
              }
            "
          >
            如需委托给供应商/文描商修改，请点击此处
          </el-link>
        </li>
      </ul>
    </div>
    <div id="wrapperContent" class="wrapper-content">
      <ul class="wrapper-ul">
        <li v-if="channelId === '0'" class="content-item">
          <base-info ref="baseInfoRef" :is-disabled="isDisabled" :from-page="'commodityLibrary'" class="baseInfo" :goods-info="goodsInfo" />
          <goodsAttribute ref="attrRef" :is-disabled="isDisabled" :from-page="'commodityLibrary'" :goods-info="goodsInfo" />
        </li>
        <li v-if="channelId === '12' || channelId === '07' || channelId === '06'" class="content-item">
          <goodsAttributes ref="attrRef" :is-disabled="isDisabled" :goods-info="goodsInfo" :channel-id="channelId" />
          <div v-if="channelId === '06'" class="categoryAttributeList">
            <el-form ref="ruleForm" class="form" label-width="120px" size="mini" label-position="left" :model="goodsInfo.skuChannelInfos[0]">
              <category-attributes
                :commodity-attribute="goodsInfo.skuChannelInfos[0]"
                :category-attributes="categoryAttributeList"
                :is-disabled="isDisabled"
                att-name="类目属性"
                :gutter="80"
                :span="12"
                :xl="8"
              />
            </el-form>
          </div>
        </li>
        <li class="content-item">
          <goodsPhoto
            ref="goodsPhotoRef"
            :is-disabled="isDisabled"
            :channel-id="channelId"
            :process-id="processId"
            :resource-diff-flag="differenceComparison(resourceDiffFlagList, 1, 'Y')"
            :from-page="'commodityLibrary'"
            :goods-photos="goodsPhotos"
            :build-standard="buildStandard"
            @goJumpDown="goJumpDown"
            @onLoadeImgs="onLoadeImgs"
          />
        </li>
        <li class="content-item">
          <detailPage
            ref="detailPageRef"
            :is-disabled="isDisabled"
            :channel-id="channelId"
            :process-id="processId"
            :from-page="'commodityLibrary'"
            :goods-info="goodsInfo.skuChannelInfos[0]"
            :build-standard="buildStandard"
            :resource-diff-flag="differenceComparison(resourceDiffFlagList, 3, 'Y')"
          />
        </li>
        <li v-for="(item, index) in skuChannelInfos.Channel2" :key="index" class="content-item">
          <storeInfo :ref="'storeInfo' + index" :is-disabled="isDisabled" :commodity-attribute="item" :gutter="0" />
          <!-- <goodsPhoto ref="goodsPhotoRef" :is-disabled="isDisabled" :goods-photos="goodsPhotos2[index]" />
          <detailPage ref="detailPageRef" :is-disabled="isDisabled" :goods-info="item" /> -->
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { Loading } from 'element-ui'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import BScroll from 'better-scroll'
import baseInfo from '@/views/coi/making/baseInfo.vue'
import goodsAttribute from '@/views/coi/making/goodsAttribute.vue'
import goodsAttributes from '@/views/coi/commodityM/components/goodsAttributes.vue'
import goodsPhoto from '@/views/coi/making/goodsPhoto.vue'
import detailPage from '@/views/coi/making/detailPage.vue'
import storeInfo from '@/views/coi/making/storeInfo.vue'
import categoryAttributes from '@/views/coi/components/categoryAttributes'
import {
  findAndSaveSkuInfoByUpcNbr,
  commodityDetail,
  findChgSkuInfoByProcessId,
  findSkuChannelInfoByChannel,
  findAndSaveSkuChannelInfoByChannel
} from '@/api/coi/onlineTaskAPI/sku'
import { transTemplateData, transTemplateData2 } from '@/utils/processingData.js'
import { authentication, filterSkuInfo } from '@/utils/processingData.js'
import eventBus from '@/utils/eventBus'
export default {
  name: 'MenuScroll',
  components: {
    baseInfo,
    goodsAttribute,
    goodsAttributes,
    goodsPhoto,
    detailPage,
    storeInfo,
    categoryAttributes
  },
  data() {
    return {
      isDisabled: this.$route.params.type !== 'edit',
      contentScroll: null,
      listHeight: [], // 用来存储每一个子盒子的高度
      currentIndex: 0,
      scrollY: 0,
      buildStandard: 0,
      goodsPhotos: {
        skuOptionResources: [], // 素材图
        transparentImg: [], // 透明
        skuResourcesImg: [] // 主图
      },
      goodsPhotos2: [],
      goodsInfo: {
        skuContentResources: [],
        skuContent: {
          content: ''
        },
        skuChannelInfos: []
      },
      menu: [
        { label: '商品信息', id: 0 },
        { label: '商品图片', id: 1 },
        { label: '商品详情', id: 2 }
      ],
      dynamicMenu: [],
      processId: null,
      operationCode: [],
      options: {
        target: document.querySelector('wrapperContent'),
        text: '正在压缩文件'
      },
      JSZipName: '',
      resourceDiffFlagList: [],
      categoryAttributeList: [],
      channelId: this.$route.params.channelId + '',
      isShowopenDialogVisible: {
        isShow: false,
        goodsType: ''
      },
      windowValue: window.appConfig.hiddenNewProducts
    }
  },
  computed: {
    skuChannelInfos() {
      const flag = this.$route.params.channelId === '0' && this.$route.params.type === 'detail'
      const Channel1 = flag ? this.goodsInfo.skuChannelInfos.filter((item) => item.channelId === '0') : [] // 渠道商品属性
      const Channel2 = flag ? this.goodsInfo.skuChannelInfos.filter((item) => item.channelId !== '0') : [] // 类目属性
      return { Channel1, Channel2 }
    }
    // channelId() {
    //   return this.$route.params.channelId + ''
    // }
  },
  created() {
    // if (this.$route.params.type === 'detail') {
    //   this.menu = this.menu.splice(0, 1)
    // }
    this.queryData(this.$route.params.type)
  },
  beforeDestroy() {
    if (this.contentScroll) this.contentScroll.destroy()
  },
  methods: {
    refreshScroll() {
      const _this = this
      const resizeObserver = new ResizeObserver((entries) => {
        _this.contentScroll && _this.contentScroll.refresh && _this.contentScroll.refresh()
        this.getHeightList()
      })
      resizeObserver.observe(document.querySelector('.wrapper-ul'))
    },
    submitForm() {
      let flag = null
      this.$refs.ruleForm.validate((valid) => {
        flag = valid
      })
      return flag
    },
    // 路由跳转(补充渠道信息)
    goAddInformation(idList, type) {
      const query = {
        idList,
        type
      }
      this.$router.push({
        path: '/VendoraddInformation_Vendor',
        query
      })
    },
    async initData(type) {
      const upcNbr = this.$route.params.upc
      if (this.$route.params.from === 'GoodsLibrary') {
        return type === 'detail' ? await commodityDetail(upcNbr) : await findAndSaveSkuInfoByUpcNbr(upcNbr)
      }
      if (this.$route.params.from === 'ChannelInventory') {
        const param = { upc: upcNbr, channelId: this.channelId }
        return type === 'detail' ? await findSkuChannelInfoByChannel(param) : findAndSaveSkuChannelInfoByChannel(param)
      }
      if (this.$route.params.from === 'OnlineBuildingTasks') {
        return await findChgSkuInfoByProcessId(upcNbr)
      }
    },
    async queryData(type) {
      try {
        this.$emit('changeLoading', true)
        const { result } = await this.initData(type)
        this.$store.commit('entustState/ADD_ERROR_DATAS', result)
        this.setIsShow(result)
        if (result) {
          this.JSZipName = result.upc
          this.resourceDiffFlagList = Array.isArray(result.resourceDiffFlag) ? result.resourceDiffFlag : []
          this.buildStandard = result.buildStandard
          if ('transportMode' in result) result.transportMode = result.transportMode + ''
          this.goodsInfo = filterSkuInfo(result)
          if (this.$route.name === 'OnlineBuildingTasks') {
            this.isDisabled = !(this.goodsInfo.mainStatus < 9013 || this.goodsInfo.mainStatus === 9021)
          }
          if (this.goodsInfo.processType === null) this.goodsInfo.processType = 1000
          if (this.goodsInfo.goodsType === 'DROPSHIPPING' && this?.$route?.params?.from === 'ChannelInventory') this.goodsInfo.processType = 1020
          this.processId = this.goodsInfo.processId
          const photos = {
            skuOptionResources: [],
            transparentImg: [],
            skuResourcesImg: []
          }
          result.skuChannelInfos.forEach((item, index) => {
            // 过滤分类照片
            photos.skuOptionResources = item.skuOptionResources.sort((a, b) => {
              return a.sort - b.sort
            }) // 素材图
            photos.transparentImg = item.skuResources.filter((item) => item.resourceType === 3) // 透明
            photos.skuResourcesImg = item.skuResources
              .filter((p) => p.resourceType === 1)
              .sort((a, b) => {
                return a.sort - b.sort
              }) // 主图
            if (index === 0) this.goodsPhotos = JSON.parse(JSON.stringify(photos))
            this.goodsPhotos2.push(photos)
            if (this.$route.params.type === 'detail' || this.channelId !== '0') {
              if (Array.isArray(item.channelAttributeList)) {
                item.channelAttributeList = item.channelAttributeList.sort((item1, item2) => item1.orderSort - item2.orderSort)
                item.channelAttributeList = item.channelAttributeList.filter((_) => {
                  const flag = this.$route.params.type === 'detail'
                  if (flag) return flag
                  if (_.skuEditFlag === null) return false
                  return parseInt(_.skuEditFlag.toString().charAt(_.skuEditFlag.toString().length - 2)) === 1
                })
              }
              if (this.channelId === '0' && item.channelName && this.$route.params.type === 'detail') {
                this.dynamicMenu.push({ label: item.channelName, id: index + 3 - 0 })
              }
              if (item.skuChannelInfo) {
                const data = JSON.parse(item.skuChannelInfo)
                if (data.channelAttributeList && item.channelAttributeList.length && Array.isArray(data.channelAttributeList)) {
                  item.channelAttributeList.forEach((channelAttribute) => {
                    const index = data.channelAttributeList.findIndex((dataChannelAttribute) => dataChannelAttribute.attrId === channelAttribute.attrId)
                    if (index !== -1) channelAttribute.attrValue = data.channelAttributeList[index].attrValue
                    if (channelAttribute.sign && !channelAttribute.attrValue && this.goodsInfo[channelAttribute.sign]) {
                      channelAttribute.attrValue = this.goodsInfo[channelAttribute.sign]
                    }
                  })
                }
                item.skuChannelInfo = null
                if (item.categoryAttributeList && data.categoryAttributeList.length && Array.isArray(data.categoryAttributeList)) {
                  item.categoryAttributeList.forEach((categoryAttribute) => {
                    const index = data.categoryAttributeList.findIndex((dataCategoryAttribute) => dataCategoryAttribute.attrId === categoryAttribute.attrId)
                    if (index !== -1) {
                      categoryAttribute.attrValue = data.categoryAttributeList[index].attrValue
                      if ('unitValue' in data.categoryAttributeList[index]) categoryAttribute.unitValue = data.categoryAttributeList[index].unitValue
                    }
                  })
                }
              }
              if (this.$route.params.type === 'detail' && this.channelId === '0') {
                item.channelCode = item.channelId
                item.channelBrandName = item.brandName
                transTemplateData2(item.categoryAttributeList)
                transTemplateData2(item.channelAttributeList)
              }
              if (this.channelId === '06') {
                item.channelBrandName = item.brandName
                transTemplateData(item.categoryAttributeList, true, false)
                transTemplateData(item.channelAttributeList, true, false)
                this.categoryAttributeList = Array.isArray(item.categoryAttributeList)
                  ? item.categoryAttributeList.filter((item) => item.attributeType === 3)
                  : []
              }
            }
            item.skuChannelInfo = null
          })
        }
      } catch (error) {
        if (error.code && error.code === '-701') {
          this.$message({
            type: 'error',
            message: error.message + '。请到商品库进行编辑补充缺失属性！',
            duration: 3 * 1000
          })
          eventBus.$emit('closeTag', this.$route)
        }
      } finally {
        this.$emit('changeLoading', false)
        this.$nextTick(() => {
          this.getHeightList()
          this.initScroll()
        })
      }
    },
    setIsShow(data) {
      if (!data.goodsType) {
        this.isShowopenDialogVisible.goodsType = '暂无商品类型'
        return false
      }
      const params = this.$route.params
      if (params.from === 'GoodsLibrary') {
        if (this.$route.params.type === 'edit') {
          if (data.goodsType === 'NORMAL' || data.goodsType === 'PB' || data.goodsType === 'DI') {
            this.isShowopenDialogVisible.isShow = true
            this.isShowopenDialogVisible.goodsType = data.goodsType
          } else {
            this.isShowopenDialogVisible.goodsType = data.goodsType
          }
        } else {
          return
        }
      } else {
        return
      }
    },

    // 判断该数据是否包含有图片类型的
    differenceComparison(list, type, diffFlag) {
      if (this.isDisabled) return []
      const lists = list.filter((_) => Number(_.resourceType) === Number(type))
      if (!diffFlag) return lists
      else return lists.filter((item) => item.diffFlag === diffFlag)
    },

    initScroll() {
      const content = document.querySelector('.wrapper-content')
      this.contentScroll = new BScroll(content, {
        click: true, // 因为betterscroll默认会阻止点击事件。这里要设置一下
        mouseWheel: true, // 鼠标滚轮滚动
        probeType: 3,
        scrollY: true,
        scrollbar: {
          fade: false, // 是否显示滚动条
          interactive: false // 1.8.0 新增
        },
        preventDefault: true, // 阻止了浏览器默认选中行为
        preventDefaultException: { className: /^elImg$/, tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|AUDIO|IMG)$/ },
        tagException: { className: /^elImg$/, tagName: /^IMG$/ }
      })
      this.refreshScroll()
      // 获取滚动的值，赋值给scrollY
      this.contentScroll.on('scroll', (pos) => {
        this.scrollY = Math.abs(Math.round(pos.y))
      })
    },
    getCurrentIndex() {
      for (let i = 0; i < this.listHeight.length; i++) {
        const height = this.listHeight[i]
        const height1 = this.listHeight[i + 1]
        // 解决当滚动到最后时，内容不足盒子高度时，菜单显示问题。当滚动到最后，选中最后一个菜单
        // maxScrollY：最大纵向滚动位置
        if (Math.abs(this.contentScroll.maxScrollY) === Math.abs(this.scrollY)) {
          return [...this.menu, ...this.dynamicMenu].length - 1
        }
        if (!height1 || (this.scrollY < height1 && this.scrollY >= height)) {
          return i
        }
      }
    },
    handleClick(index) {
      const content = document.querySelector('.wrapper-content')
      const contentList = content.getElementsByClassName('content-item')
      const el = contentList[index]
      // scrollToElement：滚动到目标元素
      this.contentScroll.scrollToElement(el, 300)
    },
    getHeightList() {
      this.listHeight = []
      let height = 0
      this.listHeight.push(height)
      const content = document.querySelector('.wrapper-content')
      if (!content) return
      const contentList = content.getElementsByClassName('content-item') || []
      for (let i = 0; i < contentList.length; i++) {
        const item = contentList[i]
        height += item.clientHeight
        this.listHeight.push(height)
      }
    },
    async onLoadeImgs() {
      console.log('goodsPhotos', this.goodsPhotos)
      const skuResourcesImg = this.goodsPhotos.skuResourcesImg // 主图
      const skuOptionResources = this.goodsPhotos.skuOptionResources // 素材图
      const skuContentResources = this.goodsInfo.skuChannelInfos[0].skuContentResources // 详情图
      const transparentImg = this.goodsPhotos.transparentImg // 透明图
      const arrImages = [
        ...this.addImageMinx(skuResourcesImg, '主图'),
        ...this.addImageMinx(skuOptionResources, '素材图'),
        ...this.addImageMinx(transparentImg, '透明图'),
        ...this.addImageMinx(skuContentResources, '详情图')
      ]
      console.log('arrImages', arrImages)
      this.filesToRar(arrImages, this.JSZipName)
      Loading.service(this.options)
    },
    addImageMinx(list, imgName) {
      const arrImages = []
      for (let i = 0; i < list.length; i++) {
        const obj = {}
        obj.fileUrl = authentication(list[i].resourceUrl)
        obj.renameFileName = `${imgName}-${i + 1}`
        arrImages.push(obj)
      }
      return arrImages
    },
    filesToRar(arrImages, filename) {
      const _this = this
      const zip = new JSZip()
      const cache = {}
      const promises = []
      for (const item of arrImages) {
        const promise = _this.getImgArrayBuffer(item.fileUrl).then((data) => {
          // 下载文件, 并存成ArrayBuffer对象(blob)
          // console.log('data', data)
          const suffix = data.type.split('/')[1]
          zip.file(`${item.renameFileName}.${suffix}`, data, { binary: true }) // 逐个添加文件
          cache[item.renameFileName] = data
        }).catch((error) => {
          throw new Error(error)
        })
        promises.push(promise)
      }
      const loadingInstance = Loading.service(this.options)
      Promise.all(promises)
        .then(() => {
          zip.generateAsync({ type: 'blob' }).then((content) => {
            // 生成二进制流
            FileSaver.saveAs(content, filename) // 利用file-saver保存文件  自定义文件名
            _this.$nextTick(() => {
              // 以服务的方式调用的 Loading 需要异步关闭
              loadingInstance.close()
            })
            _this.$message({
              showClose: true,
              message: '图片批量下载成功',
              type: 'success'
            })
          })
        })
        .catch((res) => {
          console.error(res)
          _this.$nextTick(() => {
            // 以服务的方式调用的 Loading 需要异步关闭
            loadingInstance.close()
          })
          _this.$message.error('文件生成失败了')
        })
    },
    getImgArrayBuffer(url) {
      // const _this = this
      return new Promise((resolve, reject) => {
        // 通过请求获取文件blob格式
        const xmlhttp = new XMLHttpRequest()
        xmlhttp.open('GET', url, true)
        xmlhttp.responseType = 'blob'
        xmlhttp.onload = function () {
          if (this.status === 200) {
            resolve(this.response)
          } else {
            reject(this.status)
          }
        }
        xmlhttp.onerror = () => reject()
        xmlhttp.send()
      })
    },
    // 跳转
    goJumpDown(id) {
      const router = this.$route
      const url = `/commodityM/commodityEdit/${router.params.upc}/detail/${router.params.from}/${id}?tab=''`
      console.log(url)
      this.$router.push(url)
    }
  }
}
</script>

<style scoped lang="scss">
.wrapper-scroll {
  height: 100%;
  overflow: hidden;
  margin: 0 auto;
}
.menu {
  // height: 100%;
  ul {
    display: flex;
    li {
      margin-right: 15px;
      list-style: none;
    }
  }
}
.wrapper-content {
  flex: 1;
  height: calc(100% - 70px);
  overflow: hidden;
  position: relative;
}
.active {
  border-color: #409eff;
  background: #409eff;
  color: #fff;
}
.content-item {
  &:first-child {
    padding-bottom: 0;
  }
  &:last-child {
    border-bottom: none;
  }
  padding: 20px 0;
  margin-right: 20px;
  border-bottom: 1px dashed #d9d9d9;
  .baseInfo {
    border-bottom: 1px dashed #d9d9d9;
    margin-bottom: 20px;
  }
}
.el_button_text {
  color: #606266;
}
/deep/ .el-input.is-disabled .el-input__inner {
  color: #666;
}

/deep/ .el-form-item__label::before {
  content: '*';
  margin-right: 4px;
  color: #fff;
}
ul > li {
  list-style: none;
}
.storeInfo /deep/ .el-form-item {
  max-width: 450px;
}
/deep/.head {
  font-weight: bold !important;
}
.categoryAttributeList {
  .form {
    margin: 0 10px;
    margin-top: 20px;
  }
  /deep/ .el-form-item {
    max-width: 400px;
  }

  /deep/ .el-select {
    width: 100% !important;
  }
  /deep/.el-date-editor {
    width: 100% !important;
  }
  .flex {
    display: flex;
    justify-items: space-between;
  }
  /deep/ .suffix {
    margin-right: 10px;
  }
  /deep/ .el-form-item__content {
    display: flex;
    align-items: center;
  }
  .el-icon-question {
    margin-left: 10px;
    cursor: pointer;
    font-size: 16px;
  }
  /deep/ .el-col-xl-8 {
    padding-left: 40px;
    padding-right: 40px;
  }
}
</style>
